package com.lvchangqi.util;

import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.GeneratePresignedUrlRequest;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import com.netease.cloud.services.nos.transfer.TransferManager;
import com.netease.cloud.services.nos.transfer.Upload;
import com.netease.cloud.services.nos.transfer.model.UploadResult;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * Created by version on 17-6-25.
 */
@Component
public class Uploading {
    private static final String accesskey = "53c5fde1d8b74c9e8edd79bba185b598";
    private static final String secretKey = "660740fb2ce14b5d89884dceb338bbba";
    private static final String endPoint = "nos-eastchina1.126.net";
    private static final String bucket = "bucket-vacate";
    private static final String ContentEncoding = "UTF-8";
    private static final String CacheControl = "public";
    private static final String ContentLanguage = "zh-cn";

    private static final Credentials credentials;
    private static final NosClient nosClient;
    private static final TransferManager transfer;

    static {
        credentials = new BasicCredentials(accesskey, secretKey);
        nosClient = new NosClient(credentials);
        nosClient.setEndpoint(endPoint);
        transfer = new TransferManager(nosClient);
    }

    public URL upload(InputStream in, String fileType, String name) throws InterruptedException {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setLastModified(new Date());
        metadata.setContentType(fileType);
        Upload upload = transfer.upload(bucket, name, in, metadata);
        UploadResult result = upload.waitForUploadResult();
        return this.generatedSharedUrl(result.getBucketName(), result.getKey());
    }

    /**
     * 生成下载链接(共享)
     *
     * @param bucketName 容器名
     * @param key        文件名
     * @return
     */
    public URL generatedSharedUrl(String bucketName, String key) {
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        return nosClient.generatePresignedUrl(urlRequest);
    }

}
